﻿using Se.Log;
using Se.Net.Sockets;
using Se.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using Se.Model.Generator;
using Se.Protocol;

namespace SeClient
{
    public class WorldNet
    {
        public SocketClient Socket { get; private set; }

        public ClientReceivedHandler ReceivedHandler;

        public WorldNet(string ip, int port)
        {
            this.Socket = new SocketClient(ip, port, 100, 100);
            this.Socket.DisConnected += Socket_DisConnected;
            this.Socket.ReceiveData += Socket_ReceiveData;
            var controller = new GameController();
            this.ReceivedHandler = new ClientReceivedHandler(controller);
        }

        private void Socket_ReceiveData(byte[] data)
        {
            ClientMessage commonMsg = ClientMessage.ParseFrom(data);
            this.ReceivedHandler.Handle(commonMsg);
        }

        private void Socket_DisConnected(ExSocket exSocket)
        {
            SeLog.Warn("Socket Disconnected");
        }

        /// <summary>
        /// 连接Socket
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        /// <returns></returns>
        public bool TryConnect(string ip, int port)
        {
            if (!this.Socket.Connect(new System.Net.IPEndPoint(IPAddress.Parse(ip), port)))
            {
                SeLog.Error("连接{0}服务器失败", string.Format("{0}:{1}", ip, port));
                return false;
            }
            else
            {
                SeLog.Info("服务已经连接");
            }
            return true;
        }

        /// <summary>
        /// 发送数据
        /// </summary>
        /// <param name="data"></param>
        public void SendPackage(byte[] data)
        {
            this.Socket.Send(data);
        }

    }
}
